<?php

include 'Lib/DatabaseConnection.php';
require_once("Lib/Admin.php");
require_once("Lib/Utils.php");

class DatabaseManager
{

	public $objConn;
	public $res;
	public $lastQuery = "";
	//private $dbname;

	public function __construct()
	{
		$this->objConn = NULL;
	}

	public function __destruct()
	{
		if($this->objConn != NULL)
			mysql_close($this->objConn);
	}

	public function Connect($skipAdminLogin = false)
	{
		$params = getConnectionParams();
		$this->objConn = @mysql_connect($params['Host'],$params['UserName'],$params['Password']);
		if(!$this->objConn)
			return false;
		mysql_set_charset('utf8', $this->objConn);
		if(!mysql_select_db($params['DBName'],$this->objConn))
		{
			mysql_close($this->objConn);
			$this->objConn = NULL;
			return false;
		}
		if(!$skipAdminLogin)
		{
			$admin = new Admin($this);
			if(!$admin->querySession($this))
			{
				Utils::sendTo("login.php");
				die();
			}
				
		}
		return $this->objConn;
	}

	public function SetValueToFile($fname, $value)
	{
		$lfname = getcwd() . "/mdb-database/" . $fname;
		$file = fopen($lfname,"w");
		fwrite($file,$value);
		fclose($file);
	}

	public function GetValueFromFile($fname)
	{
		$lfname = getcwd() . "/mdb-database/" . $fname;
		if(!file_exists($lfname))
			return "";
		$file = fopen($lfname,"r");
		$strtoreturn = "";
		while(!feof($file))
			$strtoreturn .= fread($file,10);
		fclose($file);
		return $strtoreturn;
	}

	public function ExcecuteSQL($sql)
	{
		return mysql_query($sql, $this->objConn);
	}

	public function GetTableFieldsList($tableName)
	{
		$params = getConnectionParams();
		$campi = mysql_list_fields($params['DBName'], $tableName, $this->objConn);
		if(!$campi)
			return FALSE;
		$colonne = mysql_num_fields($campi);
		$result = array();
		for ($i = 0; $i < $colonne; $i++)
			$result[] = mysql_field_name($campi, $i);
		return $result;
	}

	public function GetRecordsNum($table,$cond = "")
	{
		$str = "SELECT COUNT(*) AS RecordsNum FROM " . $table;
		if($cond != "")
			$str .= " WHERE ".$cond;
		$str .= " ;";
		$this->lastQuery = $str;
		$objRs = mysql_query($str,$this->objConn);
		if($objRs == FALSE)
			return FALSE;
		$res = mysql_fetch_assoc($objRs);
		if($res == FALSE)
			return FALSE;
		return $res["RecordsNum"];
	}

	public function EnumerateTableStart($table,$orderby = "",$cond = "",$limits = "")
	{
		$str = "SELECT * FROM " . $table ." ";
		if($cond != "")
			$str .= " WHERE " . $cond;
		if($orderby != "")
			$str .= " ORDER BY " . $orderby;
		if($limits != "")
			$str .= " LIMIT " . $limits;
		$str .= ";";
		$this->lastQuery = $str;
		return mysql_query($str,$this->objConn);
		/*if(odbc_fetch_row($objRs) == true)
			return $objRs;
		else
			return FALSE;*/
	}

	public function EnumerateTableStartExt($selection, $table,$orderby = "",$cond = "",$limits = "")
	{
		$str = "SELECT ".$selection." FROM " . $table ." ";
		if($cond != "")
			$str .= " WHERE " . $cond;
		if($orderby != "")
			$str .= " ORDER BY " . $orderby;
		if($limits != "")
			$str .= " LIMIT " . $limits;
		$str .= ";";
		$this->lastQuery = $str;
		return mysql_query($str,$this->objConn);
		/*if(odbc_fetch_row($objRs) == true)
			return $objRs;
		else
			return FALSE;*/
	}

	public function EnumerateTableNext($objRs)
	{
		//$this->res = FALSE;
		$this->res = mysql_fetch_assoc($objRs);
		return ($this->res != FALSE);
	}

	public function EnumerateTableGetValue($objRs,$field)
	{
		return $this->res[$field];
	}
	
	public function EnumerateTableGetValues($objRs)
	{
		return $this->res;
	}

	public function EraseRecords($table,$cond)
	{
		$str = "DELETE FROM " . $table . " WHERE " . $cond . " ;";
		$this->lastQuery = $str;
		return (mysql_query($str,$this->objConn) != FALSE);
	}

	public function GetValueFromRecords($table,$field,$cond)
	{
		//echo("SELECT " . $field . " FROM " . $table . " WHERE " . $cond . " ;");
		$objRs = NULL;
		if($cond == NULL)
		{
			$str = "SELECT " . $field . " FROM " . $table . " LIMIT 1;";
			$this->lastQuery = $str;
			$objRs = mysql_query($str,$this->objConn);
		}
		else
		{
			$str = "SELECT " . $field . " FROM " . $table . " WHERE " . $cond . " LIMIT 1 ;";
			$this->lastQuery = $str;
			$objRs = mysql_query($str,$this->objConn);
		}
		if($objRs == FALSE)
			return NULL;
		$res = mysql_fetch_assoc($objRs);
		if($res)
			return $res[$field];
		return NULL;
	}

	public function SetValueFromRecords($table,$field,$cond,$val)
	{
		//echo("UPDATE " . $table . " SET " . $field . " = " . $val . " WHERE " . $cond . " ;");
		if($cond == NULL)
		{
			$str = "UPDATE " . $table . " SET " . $field . " = " . $val . " ;";
			$this->lastQuery = $str;
			return (mysql_query($str,$this->objConn) != FALSE);
		}
		else
		{
			$str = "UPDATE " . $table . " SET " . $field . " = " . $val . " WHERE " . $cond . " ;";
			$this->lastQuery = $str;
			return (mysql_query($str,$this->objConn) != FALSE);
		}
	}

	public function GetRecord($table,$fields,$cond)
	{
		//echo("SELECT " . $field . " FROM " . $table . " WHERE " . $cond . " ;");
		$objRs = NULL;
		if($cond == NULL)
		{
			$str = "SELECT " . $fields . " FROM " . $table . " LIMIT 1;";
			$this->lastQuery = $str;
			$objRs = mysql_query($str,$this->objConn);
		}
		else
		{
			$str = "SELECT " . $fields . " FROM " . $table . " WHERE " . $cond . " LIMIT 1;";
			$this->lastQuery = $str;
			$objRs = mysql_query($str,$this->objConn);
		}
		//echo(mysql_error());
		if($objRs == FALSE)
			return NULL;
		$res = mysql_fetch_assoc($objRs);
		if($res)
			return $res;
		return NULL;
	}

	public function UpdateRecord($table,$statements,$cond)
	{
		//echo("UPDATE " . $table . " SET <br/>" . $statements . " <br/>WHERE " . $cond . " ;");
		if($cond == NULL)
		{
			$str = "UPDATE " . $table . " SET \n" . $statements . " ;";
			$this->lastQuery = $str;
			return (mysql_query($str,$this->objConn)  != FALSE);
		}
		else
		{
			$str = "UPDATE " . $table . " SET \n" . $statements . " \nWHERE " . $cond . " ;";
			$this->lastQuery = $str;
			return (mysql_query($str,$this->objConn)  != FALSE);
		}
	}

	public function AddRecord($table,$fields,$values)
	{
		//echo("INSERT INTO " . $table . " <br/>(" . $fields . ") VALUES <br/>(" . $values . ")");
		$str = "INSERT INTO " . $table . " \n(" . $fields . ") VALUES \n(" . $values . ")";
		$this->lastQuery = $str;
		return (mysql_query($str,$this->objConn) != FALSE);
	}

	public function AddRecordsWithSELECT($table,$fields,$query)
	{
		//echo("INSERT INTO " . $table . " <br/>(" . $fields . ") VALUES <br/>(" . $values . ")");
		$str = "INSERT INTO " . $table . " \n(" . $fields . ") " . $query;
		$this->lastQuery = $str;
		return (mysql_query($str,$this->objConn) != FALSE);
	}

	public function getDistinctValuesFromTableField($table,$field,$cond = NULL)
	{
		$objRs = NULL;
		if($cond == NULL)
		{
			$str = "SELECT DISTINCT " . $field . " FROM " . $table . " ;";
			$this->lastQuery = $str;
			$objRs = mysql_query($str,$this->objConn);
		}
		else
		{
			$str = "SELECT DISTINCT " . $field . " FROM " . $table . " WHERE " . $cond . " ;";
			$this->lastQuery = $str;
			$objRs = mysql_query($str,$this->objConn);
		}
		if($objRs == FALSE)
			return NULL;
		$res = mysql_fetch_assoc($objRs);
		$resValues = array();
		while($res)
		{
			$resValues[] = $res[$field];
			$res = mysql_fetch_assoc($objRs);
		}
		return $resValues;
	}

	public static function PrintValueOrNullForQuery($value)
	{
		return ($value === NULL ) ? "NULL" : $value;
	}

	public static function PrintStringOrNullForQuery($value, $quotes="'")
	{
		$val = $value;
		if($quotes == "'")
			$val = ModelUtils::escape_sq_for_SQL($val);
		else if($quotes == '"')
			$val = ModelUtils::escape_dq($val);
		return ($value === NULL || $value === "") ? "NULL" : $quotes.$val.$quotes;
	}

	public static function EncodeFieldName($fieldName)
	{
		return "`".$fieldName."`";
	}
	
	public static function CheckIsSimpleComparaison($sqlcode)
	{
		if(stripos($sqlcode, "SELECT ") !== false)
			return false;
		elseif(stripos($sqlcode, "DROP ") !== false)
			return false;
		elseif(stripos($sqlcode, "UPDATE ") !== false)
			return false;
		elseif(stripos($sqlcode, "SET ") !== false)
			return false;
		elseif(stripos($sqlcode, "INSERT ") !== false)
			return false;
		elseif(stripos($sqlcode, "DELETE ") !== false)
			return false;
		elseif(stripos($sqlcode, " FROM ") !== false)
			return false;
		return true;
	}

}

?>
